package com.ruike.alisurface.ui.payPage;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys4Utils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.adapter.PayCarListAdapter;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.utils.BannerImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.utils.ShareKey.Type_toGoshopzl;

/**
 * Author: voodoo
 * CreateDate: 2020-03-31 031 下午 09:20
 * Description: 选择支付方式
 */
public class SelectPayTypeActivity extends BaseAty {

    private static final String Tag = SelectPayTypeActivity.class.getCanonicalName();

    @BindView(R.id.selectPay_countDown_tv)
    TextView selectPayCountDownTv;
    @BindView(R.id.selectPayType_wechat_imgv)
    ImageView facePayImgv;
    @BindView(R.id.selectPayType_qrcode_imgv)
    ImageView qrcodePayImgv;

    @BindView(R.id.selectPay_goodsList_recv)
    RecyclerView selectPayGoodsListRecv;
    List<CarGoodsBeans> paycarlist;
    @BindView(R.id.img_rk_adv)
    ImageView imgRkAdv;

    @BindView(R.id.pay_type_yhmj)
    TextView payTypeYhmj;
    @BindView(R.id.pay_type_yhljm)
    TextView payTypeYhljm;
    @BindView(R.id.pay_type_mjyh)
    RelativeLayout payTypeMjyh;
    @BindView(R.id.pay_type_zklv)
    TextView payTypeZklv;
    @BindView(R.id.pay_type_zkyh)
    RelativeLayout payTypeZkyh;
    @BindView(R.id.layout_yhhd)
    LinearLayout layout_yhhd;
    @BindView(R.id.selectPay_pupdialog_tv)
    TextView selectPay_pupdialog_tv;

    static Timer timer;//计时
    ArrayList<String> aldatas = new ArrayList<>();//广告集合类
    Dialog activDialog; // 活动弹窗
    CustomDialog communicationErrorDialog; // 通讯异常弹窗
    private boolean isOpenQrCodePay;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_select_pay;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(120, selectPayCountDownTv, MainActivity.class);
    }

    @Override
    protected void initViews() {
        MchApiHttp.get_Materiel(this);
        Constant.showShop = true;
        L.i("选择支付方式页==" + this.getClass().getName());
        initTitleBar(false);

        isOpenQrCodePay = ShareUtils.getInstance().getBoolean(ShareKey.IS_OPEN_QRCODE_PAY, true);
        boolean isOpenFacePay = ShareUtils.getInstance().getBoolean(ShareKey.IS_OPEN_FACE_PAY, false);
        if (!isOpenQrCodePay) {
            qrcodePayImgv.setVisibility(View.GONE);
        }
        if (!isOpenFacePay) {
            facePayImgv.setVisibility(View.GONE);
        }

        // 活动按钮的点击
        selectPay_pupdialog_tv.setOnClickListener(v -> {
            if (activDialog != null && !activDialog.isShowing()) {
                activDialog.show();
            } else {
                aliHuoDongDialog(2);
            }
        });

    }

    @Override
    protected void initData() {
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (paycarlist != null && paycarlist.size() > 0) {
            selectPayGoodsListRecv.setLayoutManager(new GridLayoutManager(this, paycarlist.size()));
            selectPayGoodsListRecv.setHasFixedSize(true);
            selectPayGoodsListRecv.setAdapter(new PayCarListAdapter(this, paycarlist));
        }
    }

    int paytype; // 1刷脸  2扫码支付  3卡支付

    @OnClick({R.id.selectPay_goback_imgv,
            R.id.selectPayType_wechat_imgv, R.id.selectPayType_qrcode_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.selectPay_goback_imgv:
                startCountdownTimer(0, null, MainActivity.class);
                break;
            case R.id.selectPayType_wechat_imgv: // 刷脸支付
                IntentActivity(1);
                break;
            case R.id.selectPayType_qrcode_imgv: // 扫码支付
                IntentActivity(2);
                break;
        }
    }

    /**
     * 支付类型的判断 及发送能否通信的指令即返回值操作
     * 跳转到不同的页面
     *
     * @param selectPayType 选择的支付方式
     */
    private void IntentActivity(int selectPayType) {
        if (paycarlist == null) {
            showLongTip("商品数据异常，请重新选择商品", 5000);
            return;
        }
        if (BuildConfig.DEBUG) {
            EventBus.getDefault().post(new MsgEventBus(Type_toGoshopzl, ""));
        } else {
            paytype = selectPayType;
            // 通过发送灯光指令判断是否能够通讯
            Ttys4Utils.getInstance().LEDSetting(10, "0", "2", "1", 15, 15);
            if (timer == null) {
                timer = new Timer();
            }
            L.i("通信计时1====开始");
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        L.i("通信计时2====结束");
                        showCommunicationErrorDialog();
                    });
                }
            }, 3000);
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("get_materiel")) {
            try {
                selectPay_pupdialog_tv.setVisibility(View.VISIBLE);
                JSONObject jsonObject = new JSONObject(requestJsonStr);
                JSONArray data = jsonObject.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    aldatas.add(data.getString(i));
                }
                startTopAdvFileService(Constant.alAdvpath, aldatas);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("get_materiel")) {
            selectPay_pupdialog_tv.setVisibility(View.GONE);
        }
    }

    /**
     * 通讯异常提示框
     */
    private void showCommunicationErrorDialog() {
        if (communicationErrorDialog != null && communicationErrorDialog.isShowing()) {
            communicationErrorDialog.dismiss();
        }
        communicationErrorDialog = new CustomDialog.Builder(this)
                .setTitle("温馨提示").setMessage("底层通信出现异常，暂时停止购买，请稍后重试!!!")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }
                })
                .setTouchOutsideCloseDialog(false).create();
        communicationErrorDialog.show();
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_toGoshopzl)) {
            if (timer != null) {
                timer.cancel();
                timer.purge();
                timer = null;
            }
            L.i(Tag + "--购买前的通信指令---" + event.getMessage() + " =跳转类型=" + paytype);
            if (paytype == 1) {
                startActivity(PayForWeChatFaceActivity.class, null);
            } else if (paytype == 2) {
                startActivity(PayForQRCodeActivity.class, null);
            }
            finish();
        }

        if (event.getType().equals("topadv")) {
            aliHuoDongDialog(1);
        }
    }

    /**
     * 活动显示数据判断
     *
     * @param now_activity_id
     * @param activity_json
     * @throws JSONException
     */
    public void setDataHuoDong(String now_activity_id, String activity_json) throws JSONException {
        if (now_activity_id.equals("1")) {  // 转盘
            layout_yhhd.setVisibility(View.GONE);
            return;
        }
        if (TextUtils.isEmpty(activity_json)) {
            return;
        }
        JSONObject Js = new JSONObject(activity_json);
        if (now_activity_id.equals("2")) {  //满减
            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.GONE);
            String full = Js.optString("full", "");
            String reduce = Js.optString("reduce", "");
            payTypeYhmj.setText(full);
            payTypeYhljm.setText(reduce);

            return;
        }
        if (now_activity_id.equals("3")) {  //折扣
            layout_yhhd.setVisibility(View.VISIBLE);
            payTypeZkyh.setVisibility(View.VISIBLE);
            payTypeMjyh.setVisibility(View.GONE);
            String off_rate = Js.optString("off_rate", "0");
            int zhek = Double.valueOf(off_rate).intValue();
            payTypeZklv.setText(String.valueOf(zhek));

            return;
        }
    }

    /**
     * 展示阿里的活动弹窗
     *
     * @param model
     */
    public void aliHuoDongDialog(int model) {
        // 1、使用Dialog、设置style
        activDialog = new Dialog(this, R.style.Dialog);
        // 2、设置布局
        View view = View.inflate(this, R.layout.dialog_custom_layout, null);
        Banner activityBannerBanner = view.findViewById(R.id.dl_Banner_banner);
        ImageView dl_delect = view.findViewById(R.id.dl_delect);
        activityBannerBanner.setIndicatorGravity(BannerConfig.CIRCLE_INDICATOR);

        // 设置图片加载器
        activityBannerBanner.setImageLoader(new BannerImageLoader());
        // 设置banner样式
        activityBannerBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        List<String> advList = new ArrayList<>();
        for (int i = 0; i < aldatas.size(); i++) {
            String Name = aldatas.get(i).substring(aldatas.get(i).lastIndexOf("/")).substring(1);
            File file = new File(Constant.alAdvpath, Name);
            if (file.exists()) {
                advList.add(file.getAbsolutePath());
            } else {
                advList.add(aldatas.get(i));
            }
        }
        L.i("top广告活动图片地址==", advList.toString());
        // 设置图片集合
        activityBannerBanner.setImages(advList);
        // 设置自动轮播，默认为true
        activityBannerBanner.isAutoPlay(true);
        // 设置轮播时间单位毫秒
        activityBannerBanner.setDelayTime(3000);
        activityBannerBanner.start();
        activDialog.setContentView(view);
        activDialog.setCancelable(true);
        Window window = activDialog.getWindow();
        //设置弹出位置gh
        window.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = window.getAttributes();
        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        lp.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.6
        lp.height = (int) (d.getHeight() * 0.7); // 高度设置为屏幕的0.6
        window.setAttributes(lp);
        //设置对话框大小
        activDialog.show();

        dl_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dlCancal();
            }
        });

        if (model == 1) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(() -> {
                        dlCancal();
                    });
                }
            }, 3000);
        }
    }


    public void dlCancal() {
        if (activDialog != null && activDialog.isShowing()) {
            activDialog.dismiss();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Constant.showShop = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (communicationErrorDialog != null && communicationErrorDialog.isShowing()) {
            communicationErrorDialog.dismiss();
        }
        dlCancal();
    }

}
